package com.jiunuan.live.core.server.handler.impl;

import com.jiunuan.live.common.interfaces.topic.ImCoreServerProviderTopicNames;
import com.jiunuan.live.core.server.common.ImContextUtils;
import com.jiunuan.live.core.server.common.ImMsg;
import com.jiunuan.live.core.server.handler.SimplyHandler;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-10 21:52
 * @Description: 常规业务处理器
 */
@Component
@Slf4j
public class BizImMsgHandler implements SimplyHandler {
    @Resource
    private MQProducer mqProducer;
    /**
     * 消息处理函数，根据code匹配不同实现类
     *
     * @param ctx
     * @param imMsg
     */
    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        // 基本参数校验
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if(userId == null || appId == null){
            // 可能是错误的消息包导致的，直接放弃连接
            log.error("[BizImMsgHandler] attr error,imMsg: {}", imMsg);
            ctx.close();
            throw new RuntimeException("[BizImMsgHandler] attr error");
        }
        byte[] body = imMsg.getBody();
        if(body == null || body.length == 0){
            ctx.close();
            log.error("[BizImMsgHandler]消息体为空，imMsg:{}", imMsg);
            throw new RuntimeException("消息体为空");
        }

        Message message = new Message();
        message.setTopic(ImCoreServerProviderTopicNames.JIUNUAN_LIVE_IM_BIZ_MSG_TOPIC);
        message.setBody(body);
        try {
            SendResult sendResult = mqProducer.send(message);
            log.info("[BizImMsgHandler]消息发送成功,结果:{}", sendResult);
        }catch (Exception e){
            log.error("[BizImMsgHandler]消息发送失败,error:", e);
            throw new RuntimeException(e);
        }
    }
}
